﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using LprConfiger.Winform.Model;
using MiscUtil;

namespace LprConfiger.Winform
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {

        private IList<Model.Camera> _cameras = new List<Camera>();

        private Control _sysInfo;
        private Control _osd;
        private Control _camera;
        private Control _backupAndVideo;
        private Control _capCapture;
        private Control _lights;
        private Control _lanes;
        private Control _eventDetect;
        private Control _videoSpeedTest;
        private CFGPolice? _cfgPolice;
        private CFGCommon? _cfgCommon;
        private Control _currentControl;


        public Form1()
        {
            InitializeComponent();
        }

        private void barButtonItemAddCamera_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            

        }

        private void treeViewCameras_AfterSelect(object sender, TreeViewEventArgs e)
        {
           
        }

        //private void UpdateControlData(bool saveToModel)
        //{
        //    var node = treeViewCameras.SelectedNode;
        //    if (node == null) return;

        //    if (node.Tag is Camera)
        //    {
        //        UpdateCameraControlData(node.Tag as Camera, saveToModel);
        //    }
        //    else
        //    {
        //        UpdateLaneControlData(node.Tag as Lane, saveToModel);
        //    }
        //}

        //private void UpdateLaneControlData(Lane lane, bool saveToModel)
        //{
        //    if (saveToModel)
        //    {
        //        //lane.SpeedLimit = (int)lane1.speedLimit.EditValue;
        //        lane.X = (int)lane1.X.EditValue;
        //        lane.Y = (int)lane1.Y.EditValue;
        //        lane.W = (int)lane1.W.EditValue;
        //        lane.H = (int)lane1.H.EditValue;
        //    }
        //    else
        //    {
        //        //lane1.speedLimit.EditValue = lane.SpeedLimit;
        //        lane1.X.EditValue = lane.X;
        //        lane1.Y.EditValue = lane.Y;
        //        lane1.W.EditValue = lane.W;
        //        lane1.H.EditValue = lane.H;

        //    }
        //}

        //private void UpdateCameraControlData(Camera camera, bool saveToModel)
        //{
        //    if (saveToModel)
        //    {
        //        camera.StationName = (string)camera1.stationName.EditValue;
        //        camera.StationId = (string)camera1.stationId.EditValue;
        //        camera.DirectionId = (string)camera1.directionId.EditValue;
        //        camera.DirectionName = (string)camera1.directionName.EditValue;

        //        camera.Ip = (string)camera1.ip.EditValue;

        //        camera.HistoryImageCount = (int)camera1.historyImageCount.EditValue;
        //        camera.HistoryVideoCount = (int)camera1.historyVideoCount.EditValue;

        //        camera.NearCameraStretchFactor = (float)camera1.nearCameraRatio.EditValue;
        //        camera.FarCameraStretchFactor = (float)camera1.farCameraRatio.EditValue;

        //        camera.LeftTop = new Point((int)camera1.ltX.EditValue, (int)camera1.ltY.EditValue);
        //        camera.RightTop = new Point((int)camera1.rtX.EditValue, (int)camera1.rtY.EditValue);
        //        camera.LeftBottom = new Point((int)camera1.lbX.EditValue, (int)camera1.lbY.EditValue);
        //        camera.RightBottom = new Point((int)camera1.rbX.EditValue, (int)camera1.rbY.EditValue);

        //        camera.LaneWidht = (int)camera1.laneW.EditValue;
        //        camera.LaneLength = (int)camera1.laneL.EditValue;

        //        camera.PrintCaptureTime = (bool)camera1.printCaptureTime.EditValue;
        //        camera.PrintLaneNo = (bool)camera1.printLaneNo.EditValue;
        //        camera.PrintLprNo = (bool)camera1.printLprNo.EditValue;
        //        camera.PrintSpeed = (bool)camera1.printSpeed.EditValue;
        //        camera.PrintStationName = (bool)camera1.printStationId.EditValue;

        //        camera.LaneStartNo = (int)camera1.laneStartNo.EditValue;
        //    }
        //    else
        //    {
        //        camera1.stationName.EditValue = camera.StationName;
        //        camera1.stationId.EditValue = camera.StationId;
        //        camera1.directionId.EditValue = camera.DirectionId;
        //        camera1.directionName.EditValue = camera.DirectionName;

        //        camera1.ip.EditValue = camera.Ip;

        //        camera1.historyImageCount.EditValue = camera.HistoryImageCount;
        //        camera1.historyVideoCount.EditValue = camera.HistoryVideoCount;

        //        camera1.nearCameraRatio.EditValue = camera.NearCameraStretchFactor;
        //        camera1.farCameraRatio.EditValue = camera.FarCameraStretchFactor;

        //        camera1.ltX.EditValue = camera.LeftTop.X;
        //        camera1.ltY.EditValue = camera.LeftTop.Y;
        //        camera1.rtX.EditValue = camera.RightTop.X;
        //        camera1.rtY.EditValue = camera.RightTop.Y;
        //        camera1.lbX.EditValue = camera.LeftBottom.X;
        //        camera1.lbY.EditValue = camera.LeftBottom.Y;
        //        camera1.rbX.EditValue = camera.RightBottom.X;
        //        camera1.rbY.EditValue = camera.RightBottom.Y;

        //        camera1.laneW.EditValue = camera.LaneWidht;
        //        camera1.laneL.EditValue = camera.LaneLength;

        //        camera1.printCaptureTime.EditValue = camera.PrintCaptureTime;
        //        camera1.printLaneNo.EditValue = camera.PrintLaneNo;
        //        camera1.printLprNo.EditValue = camera.PrintLprNo;
        //        camera1.printSpeed.EditValue = camera.PrintSpeed;
        //        camera1.printStationId.EditValue = camera.PrintStationName;

        //        camera1.laneStartNo.EditValue = camera.LaneStartNo;
        //    }

        //}

        //private void UpdateButtonState()
        //{
        //    var cameraNodeSelected = treeViewCameras.SelectedNode.Tag is Camera;
        //    barButtonItemDelCamera.Enabled = cameraNodeSelected;
        //    barButtonItemAddLane.Enabled = cameraNodeSelected;
        //    barButtonItemDelLane.Enabled = !cameraNodeSelected;
        //}

        //private void ShowLaneControl()
        //{
        //    lane1.Visible = true;
        //    camera1.Visible = false;
        //}

        //private void ShowCameraControl()
        //{
        //    lane1.Visible = false;
        //    camera1.Visible = true;
        //}

        //private void barButtonItemAddLane_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    var n = treeViewCameras.SelectedNode;
        //    var c = (Camera)n.Tag;
        //    var l = new Lane();
        //    c.Lanes.Add(l);

        //    var ln = new TreeNode("车道");
        //    ln.Tag = l;
        //    n.Nodes.Add(ln);

        //    treeViewCameras.SelectedNode = ln;
        //}

        private void treeViewCameras_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            //UpdateControlData(true);
        }

        private void navBarItemGeneralInfo_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            //HideAllControl();

            //var control = new Controls.SystemInfo();
            //control.Dock = DockStyle.Fill;

            //panelControlContriner.Controls.Add(control);


        }

        private void navBarItem2_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            //HideAllControl();

            //var control = new Controls.Camera();
            //control.Dock = DockStyle.Fill;

            //panelControlContriner.Controls.Add(control);
        }


        private void HideAllControl()
        {
            foreach (Control control in panelControlContriner.Controls)
            {
                control.Visible = false;
            }
        }

        private void navBarItem10_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            //HideAllControl();
            //var control = new Controls.Debug();
            //control.Dock = DockStyle.Fill;

            //panelControlContriner.Controls.Add(control);
        }

        private void navBarItem8_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            //HideAllControl();
            //var control = new Controls.Lanes();
            //control.Dock = DockStyle.Fill;
            //panelControlContriner.Controls.Add(control);
        }

        private void navBarItem1_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            //HideAllControl();
            //var c = new Controls.Lights();
            //c.Dock = DockStyle.Fill;
            //panelControlContriner.Controls.Add(c);
        }

        private void navBarControl1_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            HideAllControl();

            _currentControl = null;
            if (e.Link.Item == navBarItemSystemInfo)
            {
                 _currentControl  = CreateControl(_sysInfo, typeof (Controls.SystemInfo));
                LoadSysInfo();
            }

            if (e.Link.Item == navBarItemOSD)
            {
                _currentControl = CreateControl(_osd, typeof (Controls.Osd));
                LoadOsd();
            }

            if (e.Link.Item == navBarItemCamera)
            {
                _currentControl = CreateControl(_camera, typeof (Controls.Camera));
                LoadCameras();
            }

            if (e.Link.Item == navBarItemBackupAndVideo)
            {
                _currentControl = CreateControl(_backupAndVideo, typeof (Controls.BackupAndVideo));
                LoadBackAndVideo();
            }

            if (e.Link.Item == navBarItemCarCapture)
            {
                _currentControl = CreateControl(_capCapture, typeof (Controls.Capture));
                LoadCarCapture();
            }

            if (e.Link.Item == navBarItemLights)
            {
                _currentControl = CreateControl(_lights, typeof (Controls.Lights));
                LoadLights();
            }

            if (e.Link.Item == navBarItemLanes)
            {
                _currentControl = CreateControl(_lanes, typeof (Controls.Lanes));
                LoadLanes();
            }

            if (e.Link.Item == navBarItemEventDetect)
            {
                _currentControl = CreateControl(_eventDetect, typeof (Controls.EventAndLicensePlate));
                LoadEventDetect();
            }

            if (e.Link.Item == navBarItemVideoSpeed)
            {
                _currentControl = CreateControl(_videoSpeedTest, typeof (Controls.KaKouVideoSpeedTest));
            }

            labelControlTitle.Text = e.Link.Item.Caption;

            if (_currentControl != null)
            {
                _currentControl.Visible = true;
            }
        }

        private void LoadEventDetect()
        {
            throw new NotImplementedException();
        }

        private void LoadLanes()
        {
            throw new NotImplementedException();
        }

        private void LoadLights()
        {
            throw new NotImplementedException();
        }

        private void LoadCarCapture()
        {
            var c = _currentControl as Controls.Capture;
            var cfg = _cfgPolice.Value;

            c.reportKakouData.EditValue = cfg.outputCtrl.enableGateway;
            c.reportNoPlateCar.EditValue = cfg.outputCtrl.enableNoPlate;
            c.drawTextInBanner.EditValue = cfg.outputCtrl.enableBanner;
            c.mergeImages.EditValue = cfg.outputCtrl.pictureForm;
            c.enableCaptureVideo.EditValue = cfg.outputCtrl.enableVideo;
            c.enableStoreOnDisk.EditValue = cfg.outputCtrl.enableMachine;
            c.maxImageFileSize.EditValue = cfg.outputCtrl.jpegMaxKb;
            
            c.minification.EditValue = cfg.eventDetect.minification;
            c.crossLine.EditValue = cfg.eventDetect.enableCrossLight;
            c.forbiddenType.EditValue = cfg.eventDetect.forbiddenTypes;
            c.drawDebugInfo.EditValue = cfg.eventDetect.enableDebug;

            c.enableLicenseRecognize.EditValue = cfg.reco.enable;
            c.stretchRatio.EditValue = cfg.reco.ratio;
            c.provience.EditValue = cfg.reco.province;
        }

        private void LoadBackAndVideo()
        {
            var c = _currentControl as Controls.BackupAndVideo;
            var cfg = _cfgCommon.Value;

            c.enableBackup.EditValue = cfg.backup.enable;
            c.imageBackupNumber.EditValue = cfg.backup.number;
            c.imageBackupDir.EditValue = cfg.backup.dir;
            c.imageDbPath.EditValue = cfg.backup.dbName;

            c.enableVideoRecord.EditValue = cfg.videoStore.enable;
            c.videoBackupNumber.EditValue = cfg.videoStore.maxDay;
            c.videoFileMinutes.EditValue = cfg.videoStore.timePerFile;
            c.videoStorePath.EditValue = cfg.videoStore.dir;
            c.videoDbPath.EditValue = cfg.videoStore.dbName;


        }

        private void LoadSysInfo()
        {
            var c = _currentControl as Controls.SystemInfo;
            if (_cfgCommon != null)
            {
                var cfg = _cfgCommon.Value;
                c.stationID.EditValue = cfg.baseInfo.monitorID;
                c.stationName.EditValue = cfg.baseInfo.monitorName;
                c.directionId.EditValue = cfg.baseInfo.directionID;
                c.directionName.EditValue = cfg.baseInfo.directionName;
                c.deviceId.EditValue = cfg.baseInfo.machineID;
                c.isPoliceMode.EditValue = cfg.baseInfo.isEPoliceSys;

                c.enableWatchDog.EditValue = cfg.sysCtrl.enableMonitor;
                c.enableFlowReport.EditValue = cfg.sysCtrl.enableFlowReport;
                c.flowReportInterval.EditValue = cfg.sysCtrl.intervalFlowReport;

                c.isClientMode.EditValue = cfg.sysService.bAsClient;
                c.serverIp.EditValue = cfg.sysService.serverIP;
                c.configPort.EditValue = cfg.sysService.configPort;
                c.debugPort.EditValue = cfg.sysService.debugPort;
            }
        }

        private void LoadOsd()
        {
            var c = _currentControl as Controls.Osd;
            var cfg = _cfgCommon.Value;
            c.fontColor.EditValue = cfg.text.color;
            c.fontSize.EditValue = cfg.text.fontSize;
            c.drawDeviceId.EditValue = cfg.osdFlags.drawImgMachineNo;
            c.drawRoadName.EditValue = cfg.osdFlags.drawImgAddr;
            c.drawDirectionName.EditValue = cfg.osdFlags.drawImgDirection;
            c.drawLaneNo.EditValue = cfg.osdFlags.drawImgLaneNo;
            c.drawCaptureTime.EditValue = cfg.osdFlags.drawImgTime;
            c.drawViolationType.EditValue = cfg.osdFlags.drawImgViolation;
            c.drawLicenseNumber.EditValue = cfg.osdFlags.drawImgPlate;
            c.drawLicenseColor.EditValue = cfg.osdFlags.drawImgPlateColor;
            c.drawLicenseType.EditValue = cfg.osdFlags.drawImgVehicleStyle;

            c.drawRoadNameOnVideo.EditValue = cfg.osdFlags.drawVideoDirection;
            c.drawTimeOnVideo.EditValue = cfg.osdFlags.drawVideoTime;
        }

        private void LoadCameras()
        {
            var c = _currentControl as Controls.Camera;
            var cfg = _cfgCommon.Value;

            c.cameraIp.EditValue = cfg.camera.IP;
            c.enableCameraControl.EditValue = cfg.camera.enableCtrl;
            c.imageWidth.EditValue = cfg.camera.ctrl.imageWidth;
            c.imageHeight.EditValue = cfg.camera.ctrl.imageHeight;
            c.imageFps.EditValue = cfg.camera.ctrl.imageFPS;
            c.videoWidth.EditValue = cfg.camera.ctrl.videoWidth;
            c.videoHeight.EditValue = cfg.camera.ctrl.videoHeight;
            c.videoRate.EditValue = cfg.camera.ctrl.videoRate;
        }

        private Control CreateControl(Control instance,  Type controlType)
        {
            if (instance == null)
            {
                var c = Activator.CreateInstance(controlType) as Control;
                c.Dock = DockStyle.Fill;
                panelControlContriner.Controls.Add(c);
                instance = c;
            }
           
            return instance;
        }

        private void barButtonItemConnect_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var ipPort = ((string) barEditItemIp.EditValue).Split(':');
            var ip = ipPort[0];
            var port = int.Parse(ipPort[1]);
            var packetHandler = new PacketHandler(ip, port);
            packetHandler.CommonConfigReceived += PacketHandlerOnCommonConfigReceived;
            packetHandler.PoliceConfigReceived += PacketHandlerOnPoliceConfigReceived;
        }

        private void PacketHandlerOnPoliceConfigReceived(object sender, EventArgs<CFGPolice> eventArgs)
        {
             _cfgPolice = eventArgs.Value;
        }

        private void PacketHandlerOnCommonConfigReceived(object sender, EventArgs<CFGCommon> eventArgs)
        {
            _cfgCommon = eventArgs.Value;
        }
    }
}
